import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/page/supplier/api/api_supplier.dart';
import 'package:tender_flutter/page/supplier/model/supplier_params_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/img_picker.dart';
import 'package:tender_flutter/utils/picker.dart';
import 'package:tender_flutter/utils/regex_util.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/form_widget/form_multiple_input_item.dart';
import 'package:tender_flutter/widgets/form_widget/form_option_item.dart';
import 'package:tender_flutter/widgets/form_widget/form_picture_item.dart';

class SupplierBusinessFormPage extends StatefulWidget {
  @override
  _SupplierBusinessFormPageState createState() =>
      _SupplierBusinessFormPageState();
}

class _SupplierBusinessFormPageState extends State<SupplierBusinessFormPage>
    with AutomaticKeepAliveClientMixin {
  /// Key
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  /// 行业数据
  List<CommonTagModel> _industryDatas;

  /// 表单参数
  /// type: 企业供应商
  SupplierParamsEntity _paramsEntity =
      SupplierParamsEntity(type: AppConstant.SUPPLIER_BUSINESS);

  void _preparedSubmit() {
    if (isEmpty(_paramsEntity.companyName)) {
      ToastUtils.show("请输入企业名称");
      return;
    }
    if (isEmpty(_paramsEntity.faRen)) {
      ToastUtils.show("请输入企业法人");
      return;
    }
    if (isEmpty(_paramsEntity.labelStr)) {
      ToastUtils.show("请选择企业类别");
      return;
    }
    if (isEmpty(_paramsEntity.city)) {
      ToastUtils.show("请选择城市");
      return;
    }
    if (isEmpty(_paramsEntity.contact)) {
      ToastUtils.show("请输入联系人姓名");
      return;
    }
    if (!RegexUtil.isMobileExact(_paramsEntity.phone)) {
      ToastUtils.show("请输入正确的联系电话");
      return;
    }
    if (isEmpty(_paramsEntity.remark)) {
      ToastUtils.show("请输入主营业务内容");
      return;
    }
    if (isEmpty(_paramsEntity.companyLogo)) {
      ToastUtils.show("请选择企业LOGO");
      return;
    }
    if (isEmpty(_paramsEntity.licensePic)) {
      ToastUtils.show("请选择企业营业执照");
      return;
    }
    _forSubmitted();
  }

  void _forSubmitted() async {
    LRouter.navigatorCtx(context).push(Routes.supplierCertificateListPage,
        arguments:
            SupplierCertificateListPageArguments(paramsEntity: _paramsEntity));
    // var _form = _formKey.currentState;
    // if (_form.validate()) {
    //   _form.save();
    //   // print(_username);
    //   // print(_password);
    // }
  }

  /// 获取行业类别
  Future _getIndustryCategory() async {
    if (_industryDatas != null && _industryDatas.isNotEmpty) {
      return _industryDatas;
    }
    var response =
        await ApiSupplier.getSupplierIndustryCategory<CommonListTagModel>();
    _industryDatas = response.result.xList;
    return _industryDatas;
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return _initFormData();
  }

  Widget _initFormData() {
    return SingleChildScrollView(
        child: Form(
            key: _formKey,
            child: Column(children: <Widget>[
              FormOptionItem(
                  title: "企业名称",
                  placeholder: "请输入企业名称",
                  content: _paramsEntity.companyName ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (value) {
                    _paramsEntity.companyName = value;
                    _paramsEntity.title = value;
                  }),
              FormOptionItem(
                  title: "企业法人",
                  placeholder: "请输入企业法人",
                  content: _paramsEntity.faRen ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (value) {
                    _paramsEntity.faRen = value;
                  }),
              FormOptionItem(
                  title: "行业类别",
                  placeholder: "请选择行业类别",
                  content: _paramsEntity.labelStr ?? "",
                  selectCallback: () {
                    _getIndustryCategory().then((value) => {
                          PickerUtils.showStringPicker(context,
                              data: _industryDatas.map((e) => e.title).toList(),
                              clickCallBack: (index, val) {
                            setState(() {
                              _paramsEntity.labelStr =
                                  _industryDatas[index].title;
                              _paramsEntity.labels = [
                                {"id": _industryDatas[index].id}
                              ];
                            });
                          })
                        });
                  }),
              FormOptionItem(
                  title: "所在地区",
                  placeholder: "请选择所在区域",
                  content: _paramsEntity.city ?? "",
                  selectCallback: () {
                    PickerUtils.showCityPicker(context,
                        clickCallBack: (codes, value) {
                      setState(() {
                        _paramsEntity.areaId = codes.last;
                        _paramsEntity.city = value;
                      });
                    });
                  }),
              FormOptionItem(
                  title: "详细地址",
                  placeholder: "请输入详细地址（选填）",
                  content: _paramsEntity.address ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (value) {
                    _paramsEntity.address = value;
                  }),
              FormOptionItem(
                  title: "联系人",
                  placeholder: "请输入联系人",
                  content: _paramsEntity.contact ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (value) {
                    _paramsEntity.contact = value;
                  }),
              FormOptionItem(
                  title: "联系电话",
                  placeholder: "请输入联系人电话",
                  content: _paramsEntity.phone ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.phone,
                  onChangeCallback: (value) {
                    _paramsEntity.phone = value;
                  }),
              FormOptionItem(
                  title: "微信",
                  placeholder: "请输入微信",
                  content: _paramsEntity.wxAccount ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.number,
                  onChangeCallback: (value) {
                    _paramsEntity.wxAccount = value;
                  }),
              FormMultipleInputItem(
                  title: "主营项目",
                  placeholder: "请输入主营项目（不超过1000字）",
                  content: _paramsEntity.remark ?? "",
                  onChangeCallback: (value) {
                    _paramsEntity.remark = value;
                  }),
              FormPictureItem(
                  title: "企业LOGO",
                  imgFile: _paramsEntity.companyLogo == null
                      ? null
                      : File(_paramsEntity.companyLogo),
                  callback: () {
                    ImagePickerUtils.getImage(PICKER_PHOTO).then((value) {
                      if (value != null) {
                        setState(() {
                          _paramsEntity.companyLogo = value.path;
                        });
                      }
                    });
                  }),
              FormPictureItem(
                  title: "营业执照",
                  imgFile: _paramsEntity.licensePic == null
                      ? null
                      : File(_paramsEntity.licensePic),
                  callback: () {
                    ImagePickerUtils.getImage(PICKER_PHOTO).then((value) {
                      if (value != null) {
                        setState(() {
                          _paramsEntity.licensePic = value.path;
                        });
                      }
                    });
                  }),
              _getSubmitBtn()
            ])));
  }

  /// 提交按钮
  Widget _getSubmitBtn() {
    return Container(
        height: ScreenAdapter.height(90),
        width: double.infinity,
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(50),
            horizontal: ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            color: ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: FlatButton(
            onPressed: () {
              _preparedSubmit();
            },
            child: Text("确定",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(32)))));
  }
}
